import React from 'react';
import {bem, centsToYuan} from '@/utils';
import classNames from 'classnames'

import './price.scss';

export interface PriceProps {
    color?: string;
    size?: string;
    price: number | string;
    unit?: string;
    digits?: number;
    thousands?: boolean;
    centYuan?: boolean;
}

const defaultProps = {
    color: '#fa200c',
    size: 'normal',
    price: '618.95',
    unit: '&yen;',
    digits: 2,
    thousands: false
}

const Price: React.FC<PriceProps> = (props) => {

    const { color, size, price, unit, digits, thousands, centYuan, ...rest } = {
        ...defaultProps,
        ...props
    };

    const b = bem('price');
    const showSymbol = () => {
        return { __html: unit || '' }
    }

    const checkPoint = (price: string | number) => {
        return String(price).indexOf('.') > 0
    }

    const formatThousands = (price: string | number) => {
        let num: any = price;
        if (Number(price) === 0) {
            num = 0;
        }
        // 分to元
        if (centYuan) {
            num = centsToYuan(price);
        }
        if (checkPoint(price)) {
            num = Number(price).toFixed(digits);
            let splitNum = num.split('.');
            num = typeof splitNum === 'string' ? splitNum : splitNum[0];
        } else {
            num = num.toString();

        }
        if (thousands) {
            return (num || 0).toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,')
        }
        // console.log(num)
        return num
    }

    const formatDecimal = (price: string | number) => {
        let num: any = price;
        if (Number(price) === 0) {
            num = 0;
        }
        // 分to元
        if (centYuan) {
            num = centsToYuan(price);
        }
        if (checkPoint(price)) {
            num = Number(price).toFixed(digits);
            let splitNum = num.split('.');
            num = typeof splitNum === 'string' ? 0 : splitNum[1] || 0;
        } else {
            num = 0;

        }
        const result = `0.${num}`;
        const resultFixed = Number(result).toFixed(digits);
        return String(resultFixed).substring(2, resultFixed.length);
    }

    return (
        <div className={classNames(b(), b(size))} style={{ color }}>
            {
                unit && <div className='seal-price-unit' dangerouslySetInnerHTML={showSymbol()}></div>
            }
            <div className='seal-price-integer'>{formatThousands(price)}</div>
            <div className='seal-price-decimal'>
                {
                    digits !== 0 ? <span>.</span> : ''
                }
            </div>
            <div className='seal-price-decimal'>{formatDecimal(price)}</div>
        </div>
    );
};

export default Price;